package com.revzone.demo001.PermissionModule.controller;

import com.revzone.demo001.PermissionModule.service.UserService;
import com.revzone.demo001.entity.OtherEntity.R;
import com.revzone.demo001.entity.PermissionEntity.User;
import com.revzone.demo001.utils.JwtUtils.JWTUtil;
import com.revzone.demo001.utils.RedisUtils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

/**
 *  登录界面
 * @author lsa
 * @since 2023-03-27
 */
@Api(tags = "登录管理", description = "用于登录管理的相关API")
@RestController
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;
    @Autowired
    RedisCache redisCache;

    @PostMapping("/login")
    @Operation(summary = "用户登录", parameters = {}) // 忽略 Token 参数
    public R login(@RequestBody User user) {
        R reUser = userService.getReUser(user);
        User info = (User) reUser.get("info");
        logger.info(user.getUserName()+" 该用户进行登录操作！");
        if (reUser != null && (Integer) reUser.get("code") == 200) {
//            redisCache.deleteObject(user.getUserName());
            redisCache.setCacheObject(user.getUserName(),info.getSiteId());
            return R.ok(reUser);
        }
        String a = reUser.getMsg();
        return R.error(reUser.getMsg());
    }

    @PostMapping("/refresh")
    @Operation(summary = "刷新", parameters = {}) // 忽略 Token 参数
    public R refresh(@RequestHeader("Token") String token) {
        logger.info(JWTUtil.getUsername(token)+" 该用户进行刷新操作！");
        String username = JWTUtil.getUsername(token);
        return R.ok(userService.getReUserRefresh(username));
    }

    @ApiOperation(value = "用户退出登录")
    @PostMapping("/loginOut")
    public R loginOut(@RequestHeader("Token") String token) {
        logger.info(JWTUtil.getUsername(token)+" 该用户进行登录退出操作！");
        JWTUtil.addToBlackList(token);
        return R.ok();
    }

//    @ResponseBody
//    @RequestMapping("/unauthorized/{message}")
//    public R unauthorized(@PathVariable("message") String message) throws UnsupportedEncodingException {
//        message = URLDecoder.decode(message, "UTF-8");
//        return R.error(401,message);
//    }

}

